package com.speechb.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.speechb.bean.ConstantParas;
import com.speechb.bean.UserBean;
import com.speechb.common.text.TextUtil;
import com.speechb.entity.User;
import com.speechb.mapper.dao.UserDao;
import com.speechb.modules.system.web.annotation.AuthLogin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * @author llj
 * 登录过期检测拦截器
 */
public class AuthLoginInteceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AuthLoginInteceptor.class);
    @Autowired
    UserDao<User> userDao;

    /**
     * 在业务处理器处理请求之前被调用。预处理，可以进行编码、安全控制等处理；
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod methodHandler = (HandlerMethod) handler;
            AuthLogin auth = methodHandler.getMethodAnnotation(AuthLogin.class);
            String autoLoginCode = request.getHeader("auto_login_code");
            String phoneSign = request.getHeader("phone_sign");

            if (auth != null && auth.check()) {
                if (UserBean.getUserBean() == null) {
                    response.setContentType("application/json;charset=utf-8");
                    /**
                     * 告知客户端需要登录
                     */
                    response.addHeader("auto_login", "1001");
                    Writer writer = response.getWriter();
                    Map map = new HashMap(2);
                    String userAgent = request.getHeader("User-Agent");
                    if ("accost_learn_android".equals(userAgent)) {
                        response.addHeader("mobile_code", "-10");
                    }
                    map.put("code", "-10");
                    map.put("message", "用户未登录");
                    String mapStr = JSONObject.toJSONString(map);
                    logger.debug("登录拦截器访回Json为{}", mapStr);
                    map.clear();
                    writer.write(mapStr);
                    return false;
                }
            }
            if (!TextUtil.isEmpty(phoneSign)) {
                request.getSession().setAttribute("phone_sign", phoneSign);
            }
        }
        return true;
    }

    /**
     * 在业务处理器处理请求执行完成后，生成视图之前执行。后处理（调用了Service并返回ModelAndView，但未进行页面渲染），有机会修改
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
        if (TextUtil.isEmpty(request.getSession().getAttribute(ConstantParas.PHONE_SING)) && TextUtil.isEmpty(UserBean.getUserBean())) {
            response.addHeader(ConstantParas.REQUEST_PHONE_SING, "true");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}